package com.zhongxi.guoyuan.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.UI.OffLineBaseActivity;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.LunBoUtils;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.utils.RegularTool;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.seller.offline.AddParameter;
import com.zhongxi.guoyuan.widget.view.CountTimerView;

import org.json.JSONObject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class WelcomeActivity extends OffLineBaseActivity {

    private ImageView iv;

    private CountTimerView circleView;

    @Override
    protected void init() {
        super.init();
        //获取全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_welcome);
    }

    @Override
    protected void initView() {
        super.initView();
        iv = (ImageView) findViewById(R.id.iv);
        circleView= (CountTimerView) findViewById(R.id.circleView);
        circleView.setmProgressType(CountTimerView.ProgressType.COUNT_BACK);
        MyApplication.getInstance().sharedPrefrences.edit().putString("now", String.valueOf(System.currentTimeMillis())).commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("sk", RegularTool.getRandomString(8)).commit();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE,}, 100);
        } else {
            TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            String szImei = TelephonyMgr.getDeviceId();
            MyApplication.getInstance().sharedPrefrences.edit().putString("szImei", szImei).commit();  //SSENSOR
            netWork();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        @SuppressLint("MissingPermission") String szImei = TelephonyMgr.getDeviceId();
        MyApplication.getInstance().sharedPrefrences.edit().putString("szImei", szImei).commit();
        netWork();
    }

    private void netWork() {
        unsubscribe();
        mDisposable = NetWork.getOffLineApi().welcomeApi(RelativeUrl.WELCOME + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        String mString = responseBody.string();
                        JSONObject jsonObject = new JSONObject(mString);
                        int mCode = jsonObject.optInt("code");
                        if (mCode == 1) {
                            JSONObject mExpressCode = jsonObject.optJSONObject("expressCode");
                            MyApplication.getInstance().sharedPrefrences.edit().putString("logistics", mExpressCode.toString()).commit();
                            unsubscribe();
                            getOtherNet();
                        } else if (mCode == 2816) {
                            logoutDialog();
                        } else {
                            ToastUtil.show(getString(R.string.loseData, mCode));
                            unsubscribe();
                            getOtherNet();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.show(getString(R.string.load_error));
                    }
                });
    }

    private void logoutDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(this).create();
        View view = UiUtils.inflate(R.layout.dialog_logout);
        TextView tv_Iknow = (TextView) view.findViewById(R.id.tv_Iknow);
        tv_Iknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
                    clearAppData();
                }
                unsubscribe();
                getOtherNet();
            }
        });
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                        if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
                            clearAppData();
                            finish();
                        }
                    }
                    return true;
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setView(view);
        mDialog.show();
    }

    private void clearAppData() {
        MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
        SpUtils.getInstance().saveSp("shopid", "");
        SpUtils.getInstance().saveSp("mdffline", "");
        SpUtils.getInstance().saveSp("orderid", "");
    }

    private void getOtherNet() {
        mDisposable = AddParameter.getInstance().getAdData(4)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (o instanceof AdResult) {
                            MyApplication.getInstance().setSpValue(((AdResult) o).getSafeobj());
                            if (((AdResult) o).getCode() == 1) {
                                if (((AdResult) o).getData() != null && ((AdResult) o).getData().size() > 0) {
                                    Glide.with(UiUtils.getContext())
                                            .load(Url.IMG_URL + ((AdResult) o).getData().get(0).getImage())
                                            .placeholder(R.mipmap.guide).fitCenter().into(iv);
                                    //有广告
                                    circleView.setVisibility(View.VISIBLE);
                                    circleView.start();
                                    clickAD(((AdResult) o).getData().get(0).getId(), ((AdResult) o).getData().get(0).getIsvideo(),
                                            ((AdResult) o).getData().get(0).getUrl());
                                } else {
                                   //无广告
                                    circleView.setVisibility(View.GONE);
                                    startNextActivity();
                                }
                            } else {
                                ToastUtil.show(getString(R.string.loseData, ((AdResult) o).getCode()));
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.show(getString(R.string.load_error));
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
//                        startNextActivity();
                    }
                });
    }

    private void clickAD(final String id, final int isvideo, final String url) {
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LunBoUtils.getInstance(WelcomeActivity.this).lunBoItemClickListener(id, isvideo, url);
            }
        });
    }

    private void startNextActivity() {
        startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
        finish();
    }

    @Override
    protected void initListener() {
        super.initListener();
      circleView.setProgressListener(new CountTimerView.OnProgressListener() {
          @Override
          public void onProgress(int progress) {
              if (progress==99){
                  startNextActivity();
              }
          }
      });
    }

    @Override
    protected void onStop() {
        super.onStop();
        finish();
    }

}
